package com.wjc.server.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wjc.server.dto.*;
import com.wjc.server.entity.Course;
import com.wjc.server.entity.CourseContent;
import com.wjc.server.entity.CourseExample;
import com.wjc.server.enums.CourseStatusEnum;
import com.wjc.server.mapper.CourseContentMapper;
import com.wjc.server.mapper.CourseMapper;
import com.wjc.server.mapper.MyCourseMapper;
import com.wjc.server.util.CopyUtil;
import com.wjc.server.util.SnowFlake;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


@Service
public class CourseService {
    @Resource
    private CourseMapper courseMapper;

    @Resource
    private MyCourseMapper myCourseMapper;

    @Resource
    private CourseCategoryService courseCategoryService;

    @Resource
    private CourseContentMapper courseContentMapper;

    @Resource
    private SnowFlake snowFlake;

    @Resource
    private TeacherService teacherService;

    @Resource
    private ChapterService chapterService;

    @Resource
    private SectionService sectionService;

    //查询
    public void list(CoursePageDto pageDto){
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());
        List<CourseDto> courseList=myCourseMapper.list(pageDto);
        PageInfo<CourseDto> pageInfo=new PageInfo<>(courseList);
        pageDto.setTotal(pageInfo.getTotal());
        pageDto.setList(courseList);

    }

    //保存
    @Transactional
    public void save(CourseDto courseDto){
            Date now =new Date();

        Course course=CopyUtil.copy(courseDto,Course.class);
        if (ObjectUtils.isEmpty(course.getId())){
            //新增
                course.setCreatedAt(now);
                course.setUpdatedAt(now);
            course.setId(snowFlake.nextId());
            courseMapper.insert(course);
        }else {
                     course.setUpdatedAt(now);
            courseMapper.updateByPrimaryKey(course);
        }
        //批量插入课程分类信息
        courseCategoryService.saveBatch(courseDto);
    }

    public void delete(Long id){
        courseMapper.deleteByPrimaryKey(id);
    }

    //更新课程时长
    public void updateVideoTime(Long courseId){

        myCourseMapper.updateVideoTime(courseId);
    }

    //查找课程内容
    public CourseContentDto findContent(Long id){
        CourseContent courseContent = courseContentMapper.selectByPrimaryKey(id);
        if(ObjectUtils.isEmpty(courseContent)){
            return null;
        }
        CourseContentDto courseContentDto = CopyUtil.copy(courseContent, CourseContentDto.class);
        return courseContentDto;
    }

    /*
    * 保存课程内容，包含新增和修改
    * course表有数据，若course_content表没有数据,就新增，反之则更新。
    * 先更新看看有咩有更新到数据，若没有更新到则插入，这样可以减少数据库交互。
    * */
    public int saveContent(CourseContentDto courseContentDto){
        CourseContent courseContent = CopyUtil.copy(courseContentDto, CourseContent.class);
        int i = courseContentMapper.updateByPrimaryKeyWithBLOBs(courseContent);
        if(i == 0){
            courseContentMapper.insert(courseContent);
        }
        return i;
    }


    /*
    * 更新排序
    * */
    @Transactional
    public void sort(SortDto sortDto){
        //修改当前记录的排序值
        myCourseMapper.updateSort(sortDto);

        //如果排序值变大
        if(sortDto.getNewSort() > sortDto.getOldSort()){
            //例: old=5,new=9.第一步把当前id的sort改为9，第二步排除当前id的sort，将数据库中另外的(5,9]之间的值-1.
            myCourseMapper.moveSortsForward(sortDto);
        }


        if(sortDto.getNewSort() < sortDto.getOldSort()){
            //如果排序值变小，则当前改变值与被改变值之间的数字要+1
            //例: old=9,new=5.第一步把当前id的sort改为5，第二步排除当前id的sort，将数据库中另外的[5,9)之间的值+1.
            myCourseMapper.moveSortsBackward(sortDto);
        }

    }


    /**
     * 新课列表查询，只查询已发布的，按创建日期倒序
     */
    public List<CourseDto> listNew(PageDto pageDto) {
        PageHelper.startPage(pageDto.getPage(), pageDto.getSize());
        CourseExample courseExample = new CourseExample();
        courseExample.createCriteria().andStatusEqualTo(CourseStatusEnum.PUBLISH.getCode());
        courseExample.setOrderByClause("created_at desc");
        List<Course> courseList = courseMapper.selectByExample(courseExample);
        return CopyUtil.copyList(courseList, CourseDto.class);
    }

    /**
     * 查找某一课程，供web模块用，只能查已发布的
     * @param id
     * @return
     */
    public CourseDto findCourse(Long id) {
        Course course = courseMapper.selectByPrimaryKey(id);
        if (course == null || !CourseStatusEnum.PUBLISH.getCode().equals(course.getStatus())) {
            return null;
        }
        CourseDto courseDto = CopyUtil.copy(course, CourseDto.class);

        // 查询内容
        CourseContent content = courseContentMapper.selectByPrimaryKey(id);
        if (content != null) {
            courseDto.setContent(content.getContent());
        }

        // 查找讲师信息
        TeacherDto teacherDto = teacherService.findById(courseDto.getTeacherId());
        courseDto.setTeacher(teacherDto);

        // 查找章信息
        List<ChapterDto> chapterDtoList = chapterService.listByCourse(id);
        courseDto.setChapters(chapterDtoList);

        // 查找节信息
        List<SectionDto> sectionDtoList = sectionService.listByCourse(id);
        courseDto.setSections(sectionDtoList);

        return courseDto;
    }

}
